package com.cn.wx.servlet;



import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1.创建图片对象
//             设置图片宽度
        int width=50;
        int height=20;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
//        2.美化图片
        Graphics graphics = image.getGraphics();
        graphics.setColor(new Color(238, 238, 238));
        graphics.fillRect(0,0,width,height);
//        生成随机数
        Random random=new Random();
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
       StringBuilder code=new StringBuilder();
        for(int i=0;i<4;i++){
            int index=random.nextInt(str.length());
//            获取字符
            char ch=str.charAt(index);
            code.append(ch);
            graphics.setColor(Color.red);
            graphics.drawString(ch+"",width/4*i,15);
        }
        HttpSession session = req.getSession();
        session.setAttribute("code",code.toString());
////        加边框
//        graphics.setColor(Color.blue);
//        graphics.drawRect(0,0,width-1,height-1);
//        加干扰线
//        graphics.setColor(Color.green);
//        for(int i=0;i<4;i++){
//            int x1=random.nextInt(width);
//            int x2=random.nextInt(width);
//
//            int y1=random.nextInt(height);
//            int y2=random.nextInt(height);
//            graphics.drawLine(x1,y1,x2,y2);
//        }
//        3.将图片输出到页面
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
